// 获取通用选项的label
export const getGeneralOptionsLabel = (val: any, options: any[]) => {
    for (let i in options) {
        if (options[i].value == val) {
            return options[i].label;
        }
    }
};
// 验证是否身份证
export const isIDCard = (val: any) => {
    // 正则表达式：15位或18位数字，末位为数字或者大写字母X
    let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
    return reg.test(val);
};
// 日期格式化
export const dateFormatter = (date: any) => {
    let YY = date.getFullYear() + '-';
    let MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return YY + MM + DD;
};
// 手机号
export const isPhone = (val: any) => {
    let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    return reg.test(val);
};
// 导出excel
export const downloadExcelFromBase64 = (base64Data, fileName) => {
    const byteCharacters = atob(base64Data);
    const byteNumbers = new Array(byteCharacters.length);
    for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
    }
    const byteArray = new Uint8Array(byteNumbers);
    const blob = new Blob([byteArray], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = URL.createObjectURL(blob);

    const link = document.createElement('a');
    link.href = url;
    link.download = fileName + '.xlsx';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
};

//使用递归的方式实现数组、对象的深拷贝
export const deepClone = (obj: any) => {
    let objClone = Array.isArray(obj) ? [] : {};
    if (obj && typeof obj === 'object') {
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                //判断ojb子元素是否为对象，如果是，递归复制
                if (obj[key] && typeof obj[key] === 'object') {
                    objClone[key] = deepClone(obj[key]);
                } else {
                    //如果不是，简单复制
                    objClone[key] = obj[key];
                }
            }
        }
    }
    return objClone;
};
// 根据身份证获取性别是不是男
export const getGenderIsMan = (idCard: any) => {
    if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
        return true;
    } else {
        return false;
    }
};
// 根据身份证获取出生日期
export const getBirthDate = (idCard: any) => {
    let year = idCard.slice(6, 10);
    let month = idCard.slice(10, 12);
    let day = idCard.slice(12, 14);
    return year + '-' + month + '-' + day;
};
// 检测身份证是否非法
export function isCardID(sId) {
    var aCity = {
        11: '北京',
        12: '天津',
        13: '河北',
        14: '山西',
        15: '内蒙古',
        21: '辽宁',
        22: '吉林',
        23: '黑龙江',
        31: '上海',
        32: '江苏',
        33: '浙江',
        34: '安徽',
        35: '福建',
        36: '江西',
        37: '山东',
        41: '河南',
        42: '湖北',
        43: '湖南',
        44: '广东',
        45: '广西',
        46: '海南',
        50: '重庆',
        51: '四川',
        52: '贵州',
        53: '云南',
        54: '西藏',
        61: '陕西',
        62: '甘肃',
        63: '青海',
        64: '宁夏',
        65: '新疆',
        71: '台湾',
        81: '香港',
        82: '澳门',
        91: '国外',
    };
    var iSum = 0;
    var info = '';
    if (!/^\d{17}(\d|x)$/i.test(sId)) return '身份证长度或格式错误';
    sId = sId.replace(/x$/i, 'a');
    if (aCity[parseInt(sId.substr(0, 2))] == null) return '身份证地区非法';
    let sBirthday = sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2));
    var d = new Date(sBirthday.replace(/-/g, '/'));
    if (sBirthday != d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()) return '身份证上的出生日期非法';
    for (var i = 17; i >= 0; i--) iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    if (iSum % 11 != 1) return '身份证号非法';
    //aCity[parseInt(sId.substr(0,2))]+","+sBirthday+","+(sId.substr(16,1)%2?"男":"女");//此次还可以判断出输入的身份证号的人性别
    return '';
}
// 获取性别
export function getSex(idCard) {
    //alert(idCard);
    var sexStr = '';
    if (parseInt(idCard.slice(-2, -1)) % 2 == 1) {
        sexStr = '男';
    } else {
        sexStr = '女';
    }
    return sexStr;
}
// 获取年龄
export function getAge(identityCard) {
    var len = (identityCard + '').length;
    if (len == 0) {
        return '';
    } else {
        if (len != 15 && len != 18) {
            //身份证号码只能为15位或18位其它不合法
            return '';
        }
    }
    var strBirthday = '';
    if (len == 18) {
        //处理18位的身份证号码从号码中得到生日和性别代码
        strBirthday = identityCard.substr(6, 4) + '/' + identityCard.substr(10, 2) + '/' + identityCard.substr(12, 2);
    }
    if (len == 15) {
        strBirthday =
            '19' + identityCard.substr(6, 2) + '/' + identityCard.substr(8, 2) + '/' + identityCard.substr(10, 2);
    }
    //时间字符串里，必须是“/”
    var birthDate = new Date(strBirthday);
    var nowDateTime = new Date();
    var age = nowDateTime.getFullYear() - birthDate.getFullYear();
    //再考虑月、天的因素;.getMonth()获取的是从0开始的，这里进行比较，不需要加1
    if (
        nowDateTime.getMonth() < birthDate.getMonth() ||
        (nowDateTime.getMonth() == birthDate.getMonth() && nowDateTime.getDate() < birthDate.getDate())
    ) {
        age--;
    }
    return age;
}

// 压缩图片
export class compressImg {
    //定义了一个名字为compressImg的类
    // constructor(file,num,fun){//constructor是一个构造方法，用来接收参数
    //     this.file=file;
    //     // this.num=num;
    //     // this.fun = fun
    //     // this.imgPreview(this.file,this.num)
    //     this.imgPreview(this.file)
    //     this.myf = ''
    //     this.myfb = ''
    // }
    file;
    args;
    fun;
    myf;
    myfb;
    constructor(file, fun, ...args) {
        //constructor是一个构造方法，用来接收参数
        this.file = file;
        this.args = args;
        this.fun = fun;
        this.imgPreview(this.file, '');
        this.myf = '';
        this.myfb = '';
        console.log(args);
        console.log(this.fun);
    }
    // 处理图片
    imgPreview(file, num) {
        let self = this;
        // 看支持不支持FileReader
        if (!file.file || !window.FileReader) return;
        if (/^image/.test(file.file.type)) {
            // 创建一个reader
            let reader = new FileReader();
            // 将图片2将转成 base64 格式
            reader.readAsDataURL(file.file);
            // 读取成功后的回调
            reader.onloadend = function () {
                let result = this.result as string;
                let img = new Image();
                img.src = result as string;
                //判断图片是否大于5M,是就直接上传，反之压缩图片
                if (typeof this.result === 'string' && this.result.length <= 1.5 * 1024 * 1024) {
                    console.log('图片小于1.5M');
                    // 上传图片
                    self.postImg(this.result, file, num);
                    // self.postImg(this.result, file);
                } else {
                    console.log('图片大于1.5M，需要压缩');
                    img.onload = function () {
                        let data = self.compress(img);
                        // 上传图片
                        self.postImg(data, file, num);
                        // self.postImg(data, file);
                    };
                }
            };
        }
    }
    // 压缩图片
    compress(img) {
        let canvas = document.createElement('canvas');
        let ctx = canvas.getContext('2d');
        //瓦片canvas
        let tCanvas = document.createElement('canvas');
        let tctx = tCanvas.getContext('2d');
        // let initSize = img.src.length;
        let width = img.width;
        let height = img.height;
        //如果图片大于四百万像素，计算压缩比并将大小压至400万以下
        let ratio;
        if ((ratio = (width * height) / 4000000) > 1) {
            // console.log("大于400万像素");
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        //    铺底色
        ctx.fillStyle = '#fff';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        //如果图片像素大于100万则使用瓦片绘制
        let count;
        if ((count = (width * height) / 1000000) > 1) {
            // console.log("超过100W像素");
            count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片
            //      计算每块瓦片的宽和高
            let nw = ~~(width / count);
            let nh = ~~(height / count);
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (let i = 0; i < count; i++) {
                for (let j = 0; j < count; j++) {
                    tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(img, 0, 0, width, height);
        }
        //进行压缩
        let ndata = canvas.toDataURL('image/jpeg', 0.8);
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        console.log(ndata);
        return ndata;
    }

    //将base64转换为文件
    dataURLtoFile(dataurl, file) {
        var arr = dataurl.split(','),
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return new File([u8arr], file.file.name, {
            type: file.file.type,
        });
    }

    // 提交图片到后端
    postImg(base64, file, num) {
        let filedata = this.dataURLtoFile(base64, file);
        let formData = new window.FormData();
        formData.append('file', filedata);
        // 调用传的方法
        // this.fun(formData,file,num)
        this.setMyf(formData);
        this.setMyfb(base64);
        this.fun(...this.args, base64);
    }

    getMyf() {
        return this.myf;
    }
    setMyf(myf) {
        this.myf = myf;
    }
    getMyfb() {
        return this.myfb;
    }
    setMyfb(myfb) {
        this.myfb = myfb;
    }
}
